<script setup>
import Header from  "@/components/header/Header.vue"
import HeaderSearch from "@/components/header-search/HeaderSearch.vue"
import ScenicCard from "@/components/scenic-card/ScenicCard.vue"
import ScenicCardPanda from "@/components/scenic-card/ScenicCardPanda.vue"
import HotelCart from "@/components/hotel-card/HotelCart.vue"
import HotPotCart from "@/components/Hot-Pot-cart/HotPotCart.vue"
import { computed, ref, watch } from "vue"
import api from "@/api/index.js"
import Filter from "./components/Filter.vue"
import { useRoute } from 'vue-router'
import { userStore } from '@/stores/user.js'
import { showLoadingToast, closeToast } from "vant"
import {getToken} from "@/utils/user.js"
import { filterAndRemoveDuplicates } from "@/utils/index.js"
import { useKeepalive } from "@/hooks/useKeepalive.js"

defineOptions({
  name: 'resultList',
})

const needSaveRoute = ['scenicDetail', 'hotelDetail', 'pandaScenicDetail', 'hotpotDetail']
const { scrollYEle } = useKeepalive(needSaveRoute, 'resultList')

const user = userStore()
const route = useRoute()

const refreshing = ref(false)
const list = ref([])
const totalCount = ref(0)
const loading = ref(false)
const error = ref(false)
const finished = ref(false)
const ordinaryScenicFinished = ref(false)
const pandaScenicFinished = ref(false)

const onRefresh = () => {
  params.pageNum = 1
  loading.value = true
  onLoad('下拉刷新')
}
const title = ref('景点')
let params = {}

const type = ref('')

const placeholder = computed(() => {
  if (type.value === 'attractionTickets') {
     return '请输入景点关键词'
  } else if (type.value === 'hotel') {
    return '请输入酒店关键词'
  } else {
    // return '请输入餐饮关键词'
    return '请输入活动关键词'
  }
})
const setParams = () => {
  params = {
    pageNum: 1,
    pageSize: 10,
    cityCode: user?.city?.code,
    lon: user.position?.coords?.longitude,
    lat: user.position?.coords?.latitude
  }
  const {scenicType, classifyId} = route.query
  type.value = route.query.type
  if (scenicType) {
    params.scenicType = scenicType
    if (type.value === 'attractionTickets') {
      title.value = '优质景区'
    } else if (type.value === 'hotel') {
      title.value = '优质酒店'
    } else {
      title.value = '优质店铺'
    }
  } else {
    if (type.value === 'attractionTickets') {
      title.value = '景点'
    } else if (type.value === 'hotel') {
      title.value = '酒店'
    } else {
      title.value = '店铺'
    }
  }

  if (classifyId) {
    params.scenicTypeCode = classifyId
  }
  if (classifyId === 'all') {
    delete params.scenicTypeCode
  }
}
setParams()

const _getOrdinaryScenicList = (type) => {
  if (type === 'refresh') {
    params.pageNum  = 1
    list.value = []
    pandaList.value = []
    pandaParams.pageNum = 1
  }
  ordinaryScenicFinished.value = false
  finished.value = false
  loading.value = true
  api.getScenicSpotsList(params).then((res) => {
    if (type === '下拉刷新') {
      list.value = []
      pandaList.value = []
      pandaParams.pageNum = 1
      pandaParams.cityName = user.city?.name
    }
    list.value = [...list.value, ...res.data.list]
    totalCount.value = res.data.totalCount
    params.pageNum += 1
    if (list.value.length >= res.data.totalCount) {
      ordinaryScenicFinished.value = true
      // if (getToken() && route.query?.scenicType !== '0') {
      //   _getPandaScenicList(type)
      // } else {
      //   if (list.value.length >= res.data.totalCount) {
      //     finished.value = true
      //   }
      // }
    }
  }).catch(() => {
    error.value = true
  }).finally(() => {
    refreshing.value = false
    loading.value = false
    closeToast()
  })
}

const pandaParams = {
  pageNum: 1,
  pageSize: 20,
  cityName: user.city?.name,
  id: 0
}
const pandaList = ref([])
const filterPandaList = ref([])
const _getPandaScenicList = () => {
  finished.value = false
  loading.value = true
  api.getPandaScenicList(pandaParams).then((res) => {
    finished.value = false
    if (res.data?.currPage) {
      pandaParams.pageNum = res.data.currPage += 1
    } else {
      pandaParams.pageNum += 1
    }
    const list = res.data?.list ?? []
    pandaList.value = [...pandaList.value, ...list]
    filterPandaList.value = filterAndRemoveDuplicates({arr: pandaList.value, key: 'id', county: countyActive.value})
    if (!res.data?.list) {
      // if (pandaParams.cityName && !countyActive.value) {
      //   pandaParams.cityName = ''
      //   pandaParams.pageNum = 1
      //   _getPandaScenicList()
      // } else {
      //   finished.value = true
      // }
      finished.value = true
    }
  }).catch(() => {
    error.value = true
  }).finally(() => {
    loading.value = false
  })
}

const _getHotelList = (e) => {
  finished.value = false
  loading.value = true
  api.getHotelList(params).then((res) => {
    if (e === '下拉刷新' || e === 'refresh') {
      list.value = []
    }
    params.pageNum += 1
    list.value = [...list.value, ...res.data?.list]
    if (list.value.length >= res.data.totalCount) {
      finished.value = true
    }
  }).catch(() => {
    error.value = true
  }).finally(() => {
    loading.value = false
    refreshing.value = false
  })
}
const _getHotPotList = (e) => {
  finished.value = false
  loading.value = true
  api.getHotPotList(params).then((res) => {
    if (e === '下拉刷新' || e === 'refresh') {
      list.value = []
    }
    params.pageNum += 1
    list.value = [...list.value, ...res.data?.list]
    if (list.value.length >= res.data.totalCount) {
      finished.value = true
    }
  }).catch(() => {
    error.value = true
  }).finally(() => {
    loading.value = false
    refreshing.value = false
  })
}
const onLoad = (e) => {
  if (type.value === 'attractionTickets') {
    if (e) {
      _getOrdinaryScenicList(e)
      return
    }
    if (ordinaryScenicFinished.value) {
      if (getToken()) {
        // _getPandaScenicList(e)
      }
    } else {
      _getOrdinaryScenicList(e)
    }

  } else if (type.value === 'hotel') {
    _getHotelList(e)
  } else {
    _getHotPotList(e)
  }
}
onLoad()



const isShowVanList = computed(() => {
  if ((list.value.length || pandaList.value.length) || (loading.value && !refreshing.value) || (!loading.value && error.value)) {
    return true
  }
  return false
})

watch(error, (val) => {
  if (!val) {
    loading.value = true
    onLoad()
  }
})

const emitCloseSelectClassify = (classifyId) => {
  pandaList.value = []
  pandaParams.pageNum = 1
  ordinaryScenicFinished.value = false
  if(classifyId && classifyId !== 'all') {
    params = {
      ...params,
      pageNum: 1,
      scenicTypeCode: classifyId
    }
  } else {
    delete params.scenicTypeCode
  }
  loading.value = true
  onLoad('refresh')
}

const countyActive = ref(null)
const emitChangeCity = (e) => {
  countyActive.value = e
  ordinaryScenicFinished.value = false
  if (e?.code) {
    params = {
      ...params,
      addressCode: e.code,
    }
  } else {
    delete params.addressCode
  }
  list.value = []
  pandaList.value = []
  loading.value = true
  onLoad('refresh')
}
const emitChangeSort = (e) => {
  ordinaryScenicFinished.value = false
  params = {
    ...params,
    priceSort: e
  }
  loading.value = true
  onLoad('refresh')
}

const keywords = ref([])
const search = (e) => {
  params = {
    ...params,
    pageNum: 1,
    key: e
  }
  if (e) {
    keywords.value = [e]
  }
  onLoad('refresh')
}

const watchChangeCity = ref(0)
const changeCity = () => {
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    loadingType: 'spinner'
  })
  watchChangeCity.value += 1
  loading.value = true
  pandaParams.cityName = user.city?.name
  onLoad('refresh')
}
</script>

<template>
  <div class="scenic_list_page">
    <Header :title="title" :back="true" path="/" />
    <div class="filter_search">
      <HeaderSearch
        class="header_search"
        :showIcon="true"
        :placeholder="placeholder"
        @search="search"
        @changeCity="changeCity"
      />
      <Filter
        :type="type"
        :watchChangeCity="watchChangeCity"
        @emitCloseSelectClassify="emitCloseSelectClassify"
        @emitChangeCity="emitChangeCity"
        @emitChangeSort="emitChangeSort"
      />
      <img class="scenic_bg" src="@/assets/images/index/scenic_bg.png" alt="">
    </div>
    <div class="content" ref="scrollYEle">
      <van-pull-refresh
        class="van_pull_refresh"
        v-model="refreshing"
        @refresh="onRefresh"
      >
<!--        v-if="isShowVanList"-->
        <van-list
          class="scenic_list"
          v-model:loading="loading"
          v-model:error="error"
          :finished="finished"
          finished-text="没有更多了"
          error-text="请求失败，点击重新加载"
          @load="onLoad"
        >
          <template v-if="type === 'attractionTickets'">
              <ScenicCard
                class="list"
                v-for="item in list"
                :key="item.id"
                :data="item"
                :keywords="keywords"
              />
              <ScenicCardPanda
                class="list"
                v-for="item in filterPandaList"
                :key="item.id"
                :data="item"
                :keywords="keywords"
              />
          </template>
          <template v-else-if="type === 'hotel'">
            <HotelCart
              class="list"
              v-for="item in list"
              :key="item.id"
              :data="item"
              :keywords="keywords"
            />
          </template>
          <template v-else>
            <HotPotCart
              class="list"
              v-for="item in list"
              :key="item.id"
              :data="item"
              :keywords="keywords"
            />
          </template>
        </van-list>
        <div v-show="!(list.length || filterPandaList.length) && !loading && !error">
          <div class="none">
            <img class="none_img" src="@/assets/images/index/none1.png" alt="">
            <span>暂无景点</span>
          </div>
        </div>
      </van-pull-refresh>
    </div>
  </div>
</template>

<style scoped lang="scss">
.scenic_list_page {
  display: flex;
  flex-direction: column;
  height: 100%;
  .filter_search{
    position: relative;
    .scenic_bg{
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
      width: 100%;
      height: 100%;
    }
    .header_search{
      padding: 1.5rem;
    }
  }
  .content {
    flex: 1;
    overflow-y: auto;
    .van_pull_refresh {
      min-height: 100%;
      background: #F9F8F3;
      .scenic_list {
        //height: 100%;
        //overflow-y: auto;
        .list {
          margin: 1.5rem;
        }
      }
      .none {
        display: flex;
        flex-direction: column;
        align-items: center;
        .none_img {
          width: 6rem;
          margin: 14.4rem 0 1rem 0;
        }
        span {
          font-size: 1.4rem;
          color: #666666;
        }
      }
    }
  }
}
</style>